<template>
  <div ref="chartDom"></div>
</template>
<script setup lang="ts">
import { useLocalStorage, useDebounceFn, useResizeObserver } from '@vueuse/core';
import * as echarts from 'echarts/core';
import { type EChartsOption } from 'echarts';

const props = defineProps<{
  option: EChartsOption;
  autoShowTip?: boolean;
}>();

const chartDom = ref();

let chartInstance: echarts.ECharts;
// // 适配黑色和亮色模式
const themeDarkMode = useLocalStorage('theme-dark-mode', 'auto');

// charts初始化
function renderChart() {
  chartInstance = echarts.init(chartDom.value);
  setOption();
}

function setOption() {
  chartInstance?.setOption({ darkMode: themeDarkMode.value === 'dark', ...props.option });
}

/**
 * 播放toolTip
 */
// 播放tooltip的索引
const showTipIndex = ref(0);
// 定时器timer
let autoShowTipTimer: number | undefined;

const showTipSeriesIndex = ref<any[]>([]);

/** 处理要自动播放的数据 */
function startAutoShowToolTip() {
  clearInterval(autoShowTipTimer);
  const { autoShowTip, option } = props;
  let tipIndex: number[] = [];
  // 自动展示tooltip
  if (autoShowTip) {
    if (Array.isArray(option.series) && option.series[0].type === 'pie') {
      if (Array.isArray(option.series[0].data)) {
        tipIndex = option.series[0].data.reduce((prev, current, index) => {
          if (parseFloat((current as any).value) !== 0) {
            prev.push(index);
          }
          return prev;
        }, [] as any);
      }
    } else if (option.series && !Array.isArray(option.series)) {
      tipIndex = Array.from(new Array((option.series?.data as []).length ?? 0).keys());
    }
    // 暂时只考虑饼图，如果柱状图需要自动展示在做数据筛选处理
    if (tipIndex.length > 0) {
      showTipSeriesIndex.value = tipIndex;
      autoShowTipTimer = setInterval(autoShowToolTip, 3000);
    }
  }
}
/** 自动播放数据 */
function autoShowToolTip() {
  chartInstance?.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: showTipSeriesIndex.value[showTipIndex.value],
  });
  showTipIndex.value = (showTipIndex.value + 1) % showTipSeriesIndex.value.length;
}

onMounted(() => {
  renderChart();
  startAutoShowToolTip();
});

// charts resize
useResizeObserver(
  chartDom,
  useDebounceFn(() => {
    try {
      chartInstance?.resize();
    } catch (error) {
      /* empty */
    }
  }, 300),
);

watch(
  () => props.option,
  () => {
    setOption();
    startAutoShowToolTip();
  },
);

// 组件销毁时销毁echarts
onBeforeUnmount(() => {
  chartInstance?.dispose();
});
</script>
